#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory>
#include <strings.h>
#include "InetAddr.hpp"

namespace Socket_ns
{
    class Socket;

    // 一定要 先声明，再使用 !!!
    using socket_sptr = std::shared_ptr<Socket>;

    const static int gbacklog = 8;
    enum
    {
        CREATE_SOCK = 1,
        BIND_SOCK,
        LISTEN_ERROR,
        ACCEPT_ERROR
    };

    class Socket
    {
    public:
        virtual void CreateSocket() = 0;
        virtual void SetSockAddrReuse() = 0;
        virtual void BindSocket(InetAddr &addr) = 0;
        virtual void Listen() = 0;
        virtual socket_sptr Accept(InetAddr *addr) = 0;
        virtual bool Connect(InetAddr &addr) = 0;
        virtual int Fd() = 0;
        virtual ssize_t Recv(string *out) = 0;
        virtual ssize_t Send(string &in) = 0;

    public:
        void BuildListenSock(InetAddr& addr)
        {
            CreateSocket();
            SetSockAddrReuse();
            BindSocket(addr);
            Listen();
        }

        bool BuildClientSock(InetAddr& addr)
        {
            CreateSocket();
            return Connect(addr);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket(int fd = -1) : _sockfd(fd)
        {
        }

        void CreateSocket() override
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                std::cout << "create socket failed" << std::endl;
                exit(CREATE_SOCK);
            }
        }

        void SetSockAddrReuse() override
        { 
            int reuse = 1;
            int n = setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &reuse, sizeof(reuse));
            if (n < 0)
            {
                std::cout << __LINE__ << " : setsockopt error" << std::endl;
            }
        }

        void BindSocket(InetAddr &addr) override
        {
            // int n = bind(_sockfd, (struct sockaddr *)&addr, sizeof(addr)); // 乱写！！！
            struct sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(addr.Port());
            local.sin_addr.s_addr = inet_addr(addr.Ip().c_str());

            int n = bind(_sockfd, (struct sockaddr*)&local, sizeof(local));

            if (n < 0)
            {
                std::cout << "bind failed" << std::endl;
                exit(BIND_SOCK);
            }
        }

        void Listen() override
        {
            int n = listen(_sockfd, gbacklog);
            if (n < 0)
            {
                std::cout << "listen failed" << std::endl;
                exit(LISTEN_ERROR);
            }
        }

        socket_sptr Accept(InetAddr *addr) override
        {
            struct sockaddr_in peer;
            bzero(&peer, sizeof(peer));
            socklen_t len = sizeof(peer);
            int sockfd = accept(_sockfd, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                cout << "accept failed" << endl;
                exit(ACCEPT_ERROR);
            }
            *addr = InetAddr(peer); 

            socket_sptr sptr = std::make_shared<TcpSocket>(sockfd);
            return sptr;
        }

        
        // 将 addr 与 _sockfd 连接
        bool Connect(InetAddr &addr) override
        {
            struct sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(addr.Ip().c_str());
            server.sin_port = htons(addr.Port());

            int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                cout << "connect failed" << endl;
                return false;
            }
            return true;
        }

        // int Fd() override
        int Fd() override
        {
            return _sockfd;
        }

        ssize_t Recv(string *out) override // 传入空字符串，接收信息
        {
            if (out == nullptr) return -1;
            char buffer[4096];
            ssize_t n = recv(_sockfd, buffer, sizeof(buffer), 0);
            if (n > 0)
            {
                buffer[n] = 0;
                *out = buffer;
            }
            return n;
        }

        // ssize_t Recv(string* out) override // 传入空字符串，接收信息
        // {
        //     ssize_t n = recv(_sockfd, (void*)out->c_str(), out->size(), 0);
        //     if (n < 0)
        //     {
        //         cout << "recv failed" << endl;
        //     }
        //     return n;
        // }

        ssize_t Send(string &in) override
        {
            ssize_t n = send(_sockfd, in.c_str(), in.size(), 0);
            if (n != in.size())
            {
                cout << "send failed" << endl;
            }
            return n;
        }

    private:
        int _sockfd;
    };

}